package httpapi

import (
	"context"
	"elflog/common/config"
	"elflog/component/nlog"
	controller_logger "elflog/server/httpapi/controller-logger"
	"elflog/server/httpapi/ginutil"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"time"
)

func StartHttpApi(ctx context.Context, log *nlog.NLog, cfg *config.Config, logCtrl *controller_logger.ControllerLogger) (shutDown func(waitSec time.Duration) error) {
	// 设置gin mode
	gin.SetMode(cfg.GinMode)
	// 路径设置 根路径
	RootRouter := gin.Default() // logger recover
	// 健康检查
	RootRouter.GET("health/ping", func(c *gin.Context) {
		c.String(200, "pong")
	})
	// api路由 + 中间件
	apiGroup := RootRouter.Group("/log")
	apiGroup.Use(ginutil.BuildContext())

	// 接口
	apiGroup.POST("/push_log", logCtrl.PushLog)

	// 开始服务
	srv := &http.Server{
		Addr:    ":" + strconv.Itoa(cfg.HttpPort),
		Handler: RootRouter,
	}
	go func() {
		if err := srv.ListenAndServe(); err != nil {
			log.Warnln(err)
			return
		}
	}()

	return func(waitDuration time.Duration) error {
		ctxTimeout, cancelFunc := context.WithTimeout(ctx, waitDuration)
		defer cancelFunc()
		// shutdown
		err := srv.Shutdown(ctxTimeout)
		if err != nil {
			log.Error(err)
			return err
		} else {
			log.Info("end of service...")
			return nil
		}
	}
}
